import { FC, useState, useEffect, memo, useCallback } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import classnames from 'classnames';
import styles from './style.less';
import Image from '@/components/Image';

import { bd_decrypt } from '@/utils/map';

import buttonLeft from '@/assets/map_btn_left.png';
import buttonRight from '@/assets/map_btn_right.png';
import linkIcon from '@/assets/link_icon.png';
import carIcon from '@/assets/map_icon/car.png';
import cityIcon from '@/assets/map_icon/city.png';
import companyIcon from '@/assets/map_icon/company.png';
import infoIcon from '@/assets/map_icon/info.png';
import materialsIcon from '@/assets/map_icon/materials.png';
import robotIcon from '@/assets/map_icon/robot.png';
import technologyIcon from '@/assets/map_icon/technology.png';

const setmapIcon = (type?: string) => {
  switch (type) {
    case '都市':
      return cityIcon;
    case '高端汽车':
      return carIcon;
    case '机器人':
      return robotIcon;
    case '生物技术':
      return technologyIcon;
    case '基础与新材料':
      return materialsIcon;
    case '企业':
      return companyIcon;
    case '新一代信息技术':
      return infoIcon;
    default:
      return cityIcon;
  }
};

interface Iprops {
  width?: number;
  height?: number;
  zoom?: number;
  title?: string;
  marker?: {
    lng: number;
    lat: number;
    title: string;
    id: string | number;
    type?: string;
  };
}
const Map: FC<Iprops> = (props) => {
  const [scale, setScale] = useState(1);
  const [collspan, setCollspan] = useState<boolean>(false);
  const setAppScale = function () {
    const rate = 1920 / 1080;
    const width = document.body.clientWidth * 1.0;
    const height = document.body.clientHeight * 1.0;
    if (width / height > rate) {
      setScale(1080 / height);
    } else {
      setScale(1920 / width);
    }
  };

  const { width = 548, height = 961, zoom = 13, marker, title } = props;
  const [currentMap, setCurrentMap] = useState<any>(null);
  const [currentAMap, setCurrentAMap] = useState<any>(null);
  const [currentMarker, setCurrentMarker] = useState<any>(null);
  useEffect(() => {
    AMapLoader.load({
      key: 'b85d0d6dd6242bdcdac673543d1d9f89',
      version: '',
    }).then((AMap) => {
      const map = new AMap.Map('map_container', {
        mapStyle: 'amap://styles/429d4f4bd47753a1e17054e1609cf945',
      });

      const centerPosition = bd_decrypt(116.53, 39.788);
      const position = new AMap.LngLat(centerPosition.lng, centerPosition.lat);
      map.setCenter(position);
      map.setZoom(zoom);
      setCurrentMap(map);
      setCurrentAMap(AMap);
    });
  }, [zoom]);
  useEffect(() => {
    if (currentMap && currentAMap) {
      let centerPosition: any = null;
      if (marker) {
        centerPosition = bd_decrypt(marker.lng, marker.lat);
      } else {
        centerPosition = bd_decrypt(116.53, 39.788);
      }
      const position = new currentAMap.LngLat(
        centerPosition.lng,
        centerPosition.lat,
      );
      if (currentMarker) {
        currentMap.remove(currentMarker);
      }
      currentMap.setCenter(position);
      createMarker({
        marker,
        map: currentMap,
        AMap: currentAMap,
      });
    }
  }, [marker]);
  const createMarker = useCallback(
    (obj: {
      marker?: {
        lng: number;
        lat: number;
        title: string;
        id: string | number;
        type?: string;
      };
      map: any;
      AMap: any;
    }) => {
      if (obj.map && obj.marker && obj.AMap) {
        const { map, marker, AMap } = obj;
        const markerIcon = buildMarker(
          map,
          AMap,
          marker.id,
          marker.lng,
          marker.lat,
          marker.title,
          (data) => {
            console.log(data);
            setCollspan(true);
          },
          marker.type,
        );
        setCurrentMarker(markerIcon);
        map.add(markerIcon);
      }
    },
    [],
  );

  useEffect(() => {
    setAppScale();
    window.addEventListener('resize', () => {
      setAppScale();
    });
  }, []);

  return (
    <div
      style={{
        width,
        height,
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      {title ? <div className={styles.map_title}>{title}</div> : null}
      <div
        style={{
          width: width / scale,
          height: height / scale,
          transformOrigin: '0 0',
          transform: `scale(${scale})`,
        }}
        id="map_container"
      ></div>
      {marker && (
        <div className={styles.company_warp}>
          <div
            className={classnames(
              styles.company_title,
              !collspan ? styles.hide : null,
            )}
          >
            <Image src={linkIcon} />
            <span>{marker?.title || ''}</span>
          </div>
          <Image
            src={!collspan ? buttonLeft : buttonRight}
            className={styles.company_arrow}
            onClick={() => {
              const currentCol = collspan;
              setCollspan(!currentCol);
            }}
          />
        </div>
      )}
    </div>
  );
};
export default memo(Map);

const buildMarker = (
  map: any,
  AMap: any,
  id: string | number,
  lng: number,
  lat: number,
  title: string,
  onClick: (v: any) => void,
  type?: string,
) => {
  const icon = new AMap.Icon({
    size: new AMap.Size(45, 50),
    image: setmapIcon(type),
    imageSize: new AMap.Size(45, 50),
  });
  const lnglat = bd_decrypt(lng, lat);
  const marker = new AMap.Marker({
    position: new AMap.LngLat(lnglat.lng, lnglat.lat),
    title: '北京',
    icon,
    zIndex: 200,
  });
  marker.on('mouseover', function () {
    console.log('marker mousehover');
  });

  marker.on('mouseout', function () {
    console.log('marker mouseout');
  });

  marker.on('click', function () {
    console.log(132);
    onClick({
      id,
      type,
      title,
      lat,
      lng,
    });
  });
  return marker;
};
